package com.sky.Task;

import com.sky.entity.Orders;
import com.sky.mapper.OrderMapper;
import com.sky.service.OrderService;
import lombok.extern.slf4j.Slf4j;
import net.sf.jsqlparser.expression.DateTimeLiteralExpression;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.List;

@Component
@Slf4j
public class orderTask {
    @Autowired
    private OrderMapper orderMapper;
//  每分钟触发一次
    @Scheduled(cron = "0 * * * * ?")
    public void processTimeOutOrders(){
        log.info("定时处理超时订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusMinutes(-15);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeOutList(Orders.PENDING_PAYMENT, time);
        if (ordersList.size() > 0){
            for (Orders o:ordersList) {
                o.setStatus(Orders.CANCELLED);
                o.setCancelReason("订单超时，自动取消");
                o.setCancelTime(LocalDateTime.now());
                orderMapper.update(o);
            }
        }
    }
//  每天凌晨检查
    @Scheduled(cron = "0 0 1 * * ?")
    public void processDeliveryOrders(){
        log.info("定时处理一直处于派送中的订单：{}", LocalDateTime.now());
        LocalDateTime time = LocalDateTime.now().plusHours(-1);
        List<Orders> ordersList = orderMapper.getByStatusAndOrderTimeOutList(Orders.DELIVERY_IN_PROGRESS, time);
        if (ordersList.size() > 0){
            for (Orders o:ordersList) {
                o.setStatus(Orders.CANCELLED);
                o.setCancelReason("过期订单（上一个工作日）");
                o.setCancelTime(LocalDateTime.now());
                orderMapper.update(o);
            }
        }
    }
}
